package org.fast.develop.logicflow.runtime.impl;

import org.fast.develop.logicflow.core.meta.shape.LogicFlowDefinition;
import org.fast.develop.logicflow.runtime.LogicFlowRuntimeConfiguration;
import org.fast.develop.logicflow.runtime.LogicRuntimeService;
import org.fast.develop.logicflow.runtime.cache.LogicDefinitionCache;
import org.fast.develop.logicflow.runtime.debug.ExecuteDebugConfig;
import org.fast.develop.logicflow.runtime.instance.LogicFlowInstance;
import org.fast.develop.logicflow.runtime.repository.DefinitionRepositoryEnhance;

import java.util.Map;

/**
 * @author 莫寅
 * @createTime 2022-12-20 02:45
 * @desc：
 */
public class LogicRuntimeServiceImpl implements LogicRuntimeService {

    private LogicFlowRuntimeConfiguration logicFlowRuntimeConfiguration;

    private LogicDefinitionCache logicDefinitionCache;
    private DefinitionRepositoryEnhance definitionRepositoryEnhance;


    public LogicRuntimeServiceImpl(
            LogicFlowRuntimeConfiguration logicFlowRuntimeConfiguration,
            LogicDefinitionCache logicDefinitionCache,
            DefinitionRepositoryEnhance definitionRepositoryEnhance
    ) {
        this.logicDefinitionCache = logicDefinitionCache;
        this.logicFlowRuntimeConfiguration = logicFlowRuntimeConfiguration;
        this.definitionRepositoryEnhance = definitionRepositoryEnhance;
    }

    @Override
    public LogicFlowInstance startProcessInstanceByKey(String key, Map variables) {
        byte[] bytes = logicDefinitionCache.get(key);
        String json = null;
        if(bytes == null){
            bytes = definitionRepositoryEnhance.getBytes(key);
            //缓存定义
            logicDefinitionCache.put(key, bytes);
        }

        json = new String(bytes);
        return logicFlowRuntimeConfiguration.getLogicFlowExecutor().execute(json, variables);
    }

    @Override
    public LogicFlowInstance execute(String jsonSchema, Map variables) {
        return logicFlowRuntimeConfiguration.getLogicFlowExecutor().execute(jsonSchema, variables);
    }

    @Override
    public LogicFlowInstance execute(LogicFlowDefinition logicFlowDefinition, Map variables, ExecuteDebugConfig debugConfig) {
        return logicFlowRuntimeConfiguration.getLogicFlowExecutor().execute(logicFlowDefinition, variables, debugConfig);
    }


}
